import {TileImage} from 'ol/source'
import TileGrid from 'ol/tilegrid/TileGrid'

//加载百度源
export function createBDLayerSource(params) {
  var resolutions = []
  for (var i = 0; i <= 19; i++) {
    resolutions[i] = Math.pow(2, 18 - i)
  }
  let tilegrid = new TileGrid({
    origin: [0, 0],
    resolutions: resolutions
  })
  let url = params.url
  if (params.theme === 'light') {
    url = url.replace('{theme}', process.env.VUE_APP_MAP_URL_LIGHT)
  } else {
    url = url.replace('{theme}', process.env.VUE_APP_MAP_URL_DARK)
  }
  delete params.url
  let baidu_source = new TileImage({
    ...params,
    tileGrid: tilegrid,
    tileUrlFunction: function (tileCoord, pixelRatio, projection) {
      if (!tileCoord) {
        return ''
      }
      let z = tileCoord[0]
      let x = tileCoord[1]
      let y = -tileCoord[2] - 1
      if (x < 0) x = 'M' + -x
      if (y < 0) y = 'M' + -y
      return url.replace('{x}', x).replace('{y}', y).replace('{z}', z)
    }
  })
  return baidu_source
}
